﻿using KwaiXiaoDian.Dao;
using KwaiXiaoDian.Data;
using KwaiXiaoDian.Service;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Extensions.Logging;
using Quartz;
using System;

namespace KwaiXiaoDian.Job
{
    public class MainService
    {
        IConfigurationRoot _configuration;
        IServiceProvider _serviceProvider;
        public static Logger _logger = LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 启动
        /// </summary>
        /// <returns></returns>
        public bool Start()
        {
            try
            {
                _configuration = CreateConfigurationRoot();
                _serviceProvider = CreateServiceProvider();

                using (var scope = _serviceProvider.CreateScope())
                {
                    var scheduler = scope.ServiceProvider.GetService<IScheduler>();
                    scheduler.Start().GetAwaiter().GetResult();
                }

                _logger.Info("MainService已启动");
                return true;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, string.Format("MainService启动时发生异常，message:{0}", ex.Message));
                return false;
            }
        }

        /// <summary>
        /// 停止
        /// </summary>
        /// <returns></returns>
        public bool Stop()
        {
            try
            {
                using (var scope = _serviceProvider.CreateScope())
                {
                    var scheduler = scope.ServiceProvider.GetService<IScheduler>();
                    scheduler.Shutdown().GetAwaiter().GetResult();
                }
                _logger.Info("MainService已停止");

                return true;
            }
            catch (Exception ex)
            {
                _logger.Error(ex, string.Format("MainService停止时发生异常，message:{0}", ex.Message));
                return false;
            }
        }

        /// <summary>
        /// 创建DI容器
        /// </summary>
        /// <returns></returns>
        IServiceProvider CreateServiceProvider()
        {
            IServiceCollection serviceCollection = new ServiceCollection();
            serviceCollection
                .AddSingleton<IConfiguration>(_configuration)
                .AddLogging(builder =>
                {
                    builder.ClearProviders();
                    builder.AddConfiguration(_configuration.GetSection("Logging"));
                    builder.AddConsole();
                    builder.AddNLog();
                })
                .AddQuartz(_configuration.GetSection("Quartz"))//调用Quartz扩展
                .AddServices(_configuration)
                .AddDaos()
                .AddMemoryCache()
                .AddHttpClient()
                .AddDbContext<KwaiXiaoDianDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("KwaiXiaoDianDB")));

            return serviceCollection.BuildServiceProvider();
        }

        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <returns></returns>
        IConfigurationRoot CreateConfigurationRoot()
        {
            IConfigurationBuilder builder = new ConfigurationBuilder();
            builder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false);
            return builder.Build();
        }
    }
}
